<script>
	export default {
        globalData: {
            loginToken:'',
            openid:'',
            loginUser:'',
            programType:'weixin',
            clientUrl: 'https://zycdx.fz33.net/battery',
            loginUrl:'',
            loginParaml:{},
            header: {
              'content-type': 'application/json;charset=UTF-8' // 默认值

            },
            headerPost: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            showToastLoading: function (title, mask) {
              console.log("=====showToastLoading=====", title, mask);
              if (this.programType == 'weixin') {
                uni.showLoading({
                  title: title,
                  mask: mask
                });
              }else{
                  uni.showLoading({
                    title: title,
                  });
              }
            },
            //加载失败处理
            loadFail: function () {
              let that = this;
              uni.showToast({
                title: "加载失败",
                image: '/static/tip.png',
                duration: 2000
              });
            },
            /* 处理url的函数，放到app里吧 */
            AddClientUrl: function (url, params, method, random, noToken) {
              let loginToken = this.loginToken?this.loginToken:'';
              if (noToken || !this.loginUser || !this.loginUser.loginToken) {
                loginToken = '';
              } else {
                loginToken = this.loginUser.loginToken;
              }
              let paramObj={}
              if(this.localPoint){
                  paramObj=Object.assign({},paramObj,{longitude:this.localPoint.longitude,latitude:this.localPoint.latitude})
              }
              paramObj=Object.assign({},paramObj,params)
              console.log("============================paramObj",paramObj)
              var returnUrl = this.dellUrl(url, paramObj, method, random, loginToken);
              console.log("===returnUrl===",returnUrl)
              returnUrl.url = this.clientUrl + returnUrl.url;
              console.log("returnUrl", returnUrl);
              return returnUrl;
            },
            dellUrl:function (url, params, method, random, loginToken){
              console.log("url", url)
              var post = {
                url: "",
                method: "", 
                params: {}
              }
              if (!params) {
                params = {}
              }
              if (!loginToken){
                loginToken = ''
              }
              params.loginToken = loginToken
              if (!random || method == 'post'){
                params.__ajax_random__ = Math.random();
              }
              params.mini = 1
              if(!method){
                method = "get"
              }
              if(method == "all"){
                method = post;
              }
              console.log(params)
              post.url =  url
              if (!method || method == 'get') {
                
                post.params = '?' + this.jsonToStr(params) +"&apiversion=2"
                post.url = post.url + post.params
              } else {
                post.params = params
                post.params.apiversion = 2
                post.params.jsonOnly = 1
              }
              post.method = method;
              
              console.log(post)
              return post;
            },
            jsonToStr:function  (json) {
            
              var returnParam = ""
              var str = ["jsonOnly=1"];
              for (var p in json) {
                str.push((p) + "=" + (json[p]));
              }
              returnParam += str.join("&")
              return returnParam
            },
            navigationToMap: function (info) {
              console.log("===navigationToMap===",info);
              console.log(info);
              let latitude = Number(info.latitude || info.buyerLatitude);
              let longitude = Number(info.longitude || info.buyerLongitude);
              let name = info.name || info.buyerName || info.shop_name;
              let address = info.contact_address || info.buyerProvince + info.buyerCity + info.buyerArea + info.buyerAddress; // 判断金纬度是否为空
            
              if (latitude == 0 || longitude == 0) {
                console.log("判断金纬度是否为空");
                uni.showModal({
                  title: '提示',
                  content: '主人~该门店没有设置位置哦!',
                  success: function (res) {
                    if (res.confirm) {
                      console.log('用户点击确定');
                    } else if (res.cancel) {
                      console.log('用户点击取消');
                    }
                  }
                });
                return;
              } else {
                uni.openLocation({
                  latitude: latitude,
                  longitude: longitude,
                  scale: 12,
                  name: name,
                  address: address
                });
              }
            },
            /* 微信登录测试 */
            wxLogin: function (more_scene,successFun,failFun,nextFun) {
              console.warn("===wxLogin===", more_scene);
              if (!more_scene || more_scene == 'undefined') {
                more_scene = '0';
              }
              var that = this;
              console.log('--------------微信登录--------------');
              uni.getProvider({
                  service: 'oauth',
                  success: function (res) {
                      console.log("===getProvider===",res.provider)
                      that.programType='weixin';
                      that.loginUrl='/user/wx_login'
                      if(~res.provider.indexOf('alipay')){
                          that.programType='alipay'
                          that.loginUrl='/user/zfb_login'
                      }
                      that.showToastLoading('登录中', true); 
                      uni.login({
                        //微信登入接口
                        provider: that.programType,
                        success: function (res) {
                          console.log("=======wxCode======", res.code, more_scene);
                          if (res.code && res.code.indexOf('mock') == -1) {
                            //发起网络请求
                            let loginParam = {};
                            loginParam.code = res.code;
                            loginParam.scene = more_scene;
                            that.toLogin(that.loginUrl,loginParam,successFun,failFun).then(newData =>{
                                console.log("111====登入成功====",newData)
                                if(successFun){
                                    successFun()
                                }
                                if(nextFun){
                                    nextFun()
                                }
                            });
                          } else {
                            console.log('获取用户登录态失败！' + res.errMsg);
                          }
                        },
                        fail: function (res) {
                            // 请求修改20200904
                          if(nextFun){
                              nextFun()
                          }
                          console.log('---------111111  fail登录失败----------',res);
                        },
                        complete: function (res) {
                          console.log('---------111111  complete登录结束----------',res);
                          uni.hideLoading();
                        }
                      });
                  }
              });
            },
            checkWxAuthUserInfo:function(callback,failFun){
                var that=this;
                uni.getSetting({//检查用户是否授权了
                   success(res) {
                     console.warn("======检查用户是否授权了========", res)
                     if (res.authSetting['scope.userInfo']||res.authSetting['userInfo']) {
                       console.log("已授权")
                        if(callback){
                            callback()
                        }
                     } else {
                       console.log("未授权")
                       if(failFun){
                           failFun()
                       }
                     }
                   }
                })
            },
            getStorageFun:function(keyData,successFun,failFun){
            	let that=this;
            	console.log("====获取本地存储======")
            	uni.getStorage({
            	    key: keyData,
            	    success: function (res) {
            	        console.log("==success===",res.data);
            			try{
            				successFun(res)
            			}catch(e){
            				console.log("没有成功回调的函数",e)
            				//TODO handle the exception
            			}
            	    },
            		fail:function(err){
            			console.log("====fail====",err)
            			try{
            				failFun(err)
            			}catch(e){
            				console.log("没有成功回调的函数",e)
            				//TODO handle the exception
            			}
            		},
            		complete:function(){
            			
            		}
            	});
            },
            setStorageFun:function(url,resData){
            	let that=this;
            	console.log("====本地存储======")
            	uni.setStorage({
            	    key: url,
            	    data: resData,
            	    success: function (res) {
            	        console.log('success',res);
            	    }
            	});
            },
            removeStorageFun:function(url,callback){
            	let that=this;
            	console.log("====移除本地存储======",url)
            	uni.removeStorage({
            	    key: url,
            	    success: function (res) {
            	        console.log('success',res);
                        if(callback){
                            callback(res)
                        }
            	    }
            	});
            },
            toLogin:function(url,params,successFun,failFun){
                var that = this;
                console.log("====url===",url,params)
                let customIndex = that.AddClientUrl(url, params, 'post');
                console.log("====customIndex===",customIndex)
                return new Promise(function (resolve, reject){
                    // resolve("登录中")
                    uni.request({
                      url: customIndex.url,
                      data: customIndex.params,
                      header: that.header,
                      method: 'GET',
                      success: function (e) {
                          resolve(e.data.data.openid||e.data.data);
                          console.log("===========uni.login=============", e);
                          let header = e.header;
                          let cookie = null;
                          if (!!header['Set-Cookie']) {
                            cookie = header['Set-Cookie'];
                          }
                          if (!!header['set-cookie']) {
                            cookie = header['set-cookie'];
                          }     
                          let loginJson = e.data.data;
                          console.log("====cookie====",cookie)
                          that.setCookie(cookie);
                          if (e.data.code == 0) {
                            resolve("===调用成功====");
                            that.openid=loginJson.openid||loginJson
                            // that.setStorageFun("loginToken",loginJson.platformUser.loginToken);
                            // that.loginToken=loginJson.platformUser.loginToken;
                            if(successFun){
                              successFun(e)
                            }
                            console.log('登陆成功');
                            // 把用户信息和cookie存在本地
                            that.getStorageFun("loginUser",function(res){
                                console.log("===getStorageFun===",res)
                                loginJson.nickname=res.data.nickname
                                loginJson.headimgurl=res.data.headimgurl
                                that.loginUser = loginJson;
                                that.setloginUser(loginJson);
                            },function(){
                                that.loginUser = loginJson;
                                that.setloginUser(loginJson);
                            })
                            uni.hideLoading();
                          } else {
                            console.log("失败原因" + JSON.stringify(e.data));
                            if(failFun){
                              failFun(e)
                            }
                            uni.hideLoading();
                          }
                      },
                      fail: function (e) {
                        console.log('----fail------',e);
                        if(failFun){
                          failFun(e)
                        }
                      }
                    })
                })
            },
            /* 设置cookie */
            setCookie: function (cookie) {
              console.log("===setCookie===",cookie)
              this.cookie = cookie;
              this.header = {
                'content-type': 'application/json',
                // 默认值
                'Cookie': cookie
              };
              this.headerPost = {
                'content-type': 'application/x-www-form-urlencoded',
                'Cookie': cookie
              };
              if (cookie) {
                uni.setStorage({
                  key: "cookie",
                  data: cookie
                });
              }
            },
            //存用户信息
            setloginUser: function (loginUser) {
              console.log('--------setloginUser----------');
              if (loginUser) {
                uni.setStorage({
                  key: "loginUser",
                  data: loginUser
                });
              }
            },
        },
		onLaunch: function() {
			console.log('App Launch');
            let that=this;
            // that.$options.globalData.wxLogin()
		},
		onShow: function() {
			console.log('App Show')
		},
		onHide: function() {
			console.log('App Hide')
		}
	}
</script>

<style>
	/*每个页面公共css */
    /* @import "./common/uni.css"; */
    @import "./app.css"
</style>
